#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include "tiempo.c"
#include "funcions_directorio.c"


void startDaemon(char *path, int days, int sec);
void catcher(int sig);

char dir[256];
int seg;

void startDaemon(char *path, int days, int sec) {
	seg = sec;
	strncpy(dir, path, 256);
	
	struct sigaction sact;
	
	//prepares options for sigaction (in this case, just to change what to do on SIGALRM signal)

	sigemptyset( &sact.sa_mask );
	//signals that should be avoided during the handling process
	sact.sa_flags = 0; // a set of flags which modify the behaviour of the signal handling process
	sact.sa_handler = catcher;
	
	//used to change the action taken by a process on receipt of a specific signal ("SIGALARM")
	sigaction(SIGALRM, &sact, NULL);
	
	
	char imprimir[500];
	sprintf(imprimir, "\n\n***** Arrancando filedaemon test en %s a %s *****\n", dir, getTimeAsString(getCurrentTime()));
	write(1, imprimir, strlen(imprimir));
	
	if(procesarDirectorio(dir, days, -1) == -1) {
		fputs("Detendo filedaemon debido a un erro", stderr);
		exit(EXIT_FAILURE);
	}
	
	write(1, "\n***** Detendo filedaemon *****", 31);

	while (1) {
		//arranges for a SIGALRM signal to be delivered to the process in 'sec' seconds.
		//that is, timer will pop in sec seconds.		
		alarm(sec);
		pause(); //sleep until a signal is received
	}
}

void catcher(int sig) {
	char imprimir[500];
	sprintf(imprimir, "\n\n***** Arrancando filedaemon test en %s a %s *****\n", dir, getTimeAsString(getCurrentTime()));
	write(1, imprimir, strlen(imprimir));
	
	if(procesarDirectorio(dir, -1, seg) == -1) {
		fputs("Detendo filedaemon debido a un erro", stderr);
		exit(EXIT_FAILURE);
	}

	write(1, "\n***** Detendo filedaemon *****", 31);

}


